package com.sfac.day03.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class RequestViewMappingInterceptor implements HandlerInterceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(RequestViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        LOGGER.debug("==== Pre interceptor ====");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("==== Post interceptor ====");

        // 判断 modelAndView， 排除特殊情况： 接口返回、转发、重定向
        if (modelAndView == null ||
                modelAndView.getViewName().startsWith("redirect") ||
                modelAndView.getViewName().startsWith("forward")) {
            HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
            return;
        }

        // 判断 modelmap 中是否已经设置有 template
        String path = (String) modelAndView.getModelMap().get("template");
        if (StringUtils.isBlank(path)) {
            // 如果未设置，获取 servlet path，将 path 路径设置到 modelmap 里
            String servletPath = request.getServletPath();
            if (servletPath.startsWith("/")) {
                servletPath = servletPath.substring(1);
            }
            modelAndView.getModelMap().put("template", servletPath);
        }

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        LOGGER.debug("==== After interceptor ====");
    }
}
